package com.citic.netty.common.serializer.impl;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import com.citic.netty.common.exception.NettyRuntimeException;
import com.citic.netty.common.serializer.Serializer;
import com.citic.netty.common.serializer.SerializerAlgorithm;

public class JavaSerializer implements Serializer{

	@Override
	public byte getSerializerAlogrithm() {
		return SerializerAlgorithm.JAVA;
	}

	@Override
	public byte[] serialize(Object object) {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ObjectOutputStream obj = null;
        try {
			obj = new ObjectOutputStream(out);
			obj.writeObject(object);
			return out.toByteArray();
		} catch (IOException e) {
			throw new NettyRuntimeException("java serialize error: " + e.getMessage());
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> T deserialize(Class<T> clazz, byte[] bytes) {
		ObjectInputStream ois;
		try {
			ois = new ObjectInputStream(new BufferedInputStream(new java.io.ByteArrayInputStream(bytes)));
			return (T) ois.readObject();
		} catch (Exception e) {
			throw new NettyRuntimeException("java deserialize error: " + e.getMessage());
		}
	}

}
